#include <stdio.h>

int sumSubarrayMins(int *arr, int arrSize) {
    int monStack[arrSize], left[arrSize], right[arrSize];
    int top = 0;
    for (int i = 0; i < arrSize; ++i) {
        while (top && arr[i] <= arr[monStack[top - 1]]) {
            top--;
        }
        left[i] = i - (top == 0 ? -1 : monStack[top - 1]);
        monStack[top++] = i;
    }
    top = 0;
    for (int i = arrSize - 1; i >= 0; i--) {
        while (top && arr[i] < arr[monStack[top - 1]]) {
            top--;
        }
        right[i] = (top == 0 ? arrSize : monStack[top - 1]) - i;
        monStack[top++] = i;
    }
    long long ans = 0;
    long long mod = 1e9 + 7;
    for (int i = 0; i < arrSize; ++i) {
        ans = (ans + (long long) left[i] * right[i] * arr[i]) % mod;
    }
    return ans;
}

int main() {
    int test[4] = {3, 1, 2, 4};
    int ret = sumSubarrayMins(test, 4);
    printf(" %d", ret);
}